{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python符号运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:46:07.704932Z",
     "start_time": "2022-07-21T08:46:07.691299Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X_1\n"
     ]
    },
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\lambda_{1}$"
      ],
      "text/plain": [
       "lamda_1"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import sympy as sp\n",
    "vars = sp.symbols('X_1')\n",
    "print(vars)\n",
    "lb=sp.symbols(\"lamda_1\")\n",
    "lb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:38:25.858516Z",
     "start_time": "2022-07-21T08:38:25.852519Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\frac{1}{2}$"
      ],
      "text/plain": [
       "1/2"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = sp.Rational(1, 2) # 构造分数 1/2\n",
    "z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:40:13.698511Z",
     "start_time": "2022-07-21T08:40:13.644915Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle 2$"
      ],
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = sp.symbols('x')\n",
    "expr = sp.cos(x) + 1\n",
    "expr.subs(x, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:40:49.537443Z",
     "start_time": "2022-07-21T08:40:49.389583Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle x^{2} + 2 x + 1$"
      ],
      "text/plain": [
       "x**2 + 2*x + 1"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str_expr = 'x**2 + 2*x + 1'\n",
    "expr = sp.sympify(str_expr)\n",
    "expr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:41:18.794927Z",
     "start_time": "2022-07-21T08:41:18.781949Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle 3.14$"
      ],
      "text/plain": [
       "3.14"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sp.pi.evalf(3) # pi 保留 3 位有效数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:44:24.789828Z",
     "start_time": "2022-07-21T08:44:24.774196Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8660254037844386\n"
     ]
    },
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\frac{\\sqrt{3}}{2}$"
      ],
      "text/plain": [
       "sqrt(3)/2"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "a = np.pi / 3\n",
    "x = sp.symbols('x')\n",
    "expr = sp.sin(x)\n",
    "f = sp.lambdify(x, expr, 'numpy')\n",
    "print(f(a))\n",
    "expr.subs(x, sp.pi/3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-07-21T08:45:26.070566Z",
     "start_time": "2022-07-21T08:45:26.027767Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/latex": [
       "$\\displaystyle \\sin{\\left(2 \\alpha_{\\mu} \\right)}$"
      ],
      "text/plain": [
       "sin(2*alpha_mu)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alpha_mu = sp.symbols('alpha_mu')\n",
    "sp.simplify(2*sp.sin(alpha_mu)*sp.cos(alpha_mu))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Hessian Matrix\n",
    "import sympy as sp\n",
    "import numpy as np\n",
    "\n",
    "x, y, u, v = tp = sp.symbols(\"x y u v\")\n",
    "\n",
    "f = -(2*x+3*y)\n",
    "g1 = -(4*x+6*y-6)\n",
    "g2 = -(3*x+2*y-4)\n",
    "F = f+u*g1+v*g2\n",
    "\n",
    "ls = []\n",
    "for i in (x, y):\n",
    "    ls.append(sp.diff(F, i))\n",
    "\n",
    "ls.append(u*g1)\n",
    "ls.append(v*g2)\n",
    "print(ls)\n",
    "\n",
    "print(\"Solve:\\n\", sp.solve(ls))\n",
    "# ls.clear()\n",
    "# for i in tp:\n",
    "#     for j in tp:\n",
    "#         ri = sp.diff(sp.diff(f, i), j)\n",
    "#         ls.append(ri)\n",
    "# mtx = np.array(ls).reshape([l := len(tp), l])\n",
    "# print(\"Hessian Matrix:\\n\", mtx)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "221 ns ± 1.93 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "def f(x):\n",
    "    return x ** 2 - x\n",
    "%timeit f(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "132 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "# %%cython\n",
    "from numba import jit\n",
    "@jit\n",
    "def g(x):\n",
    "    return x ** 2 - x\n",
    "%timeit g(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext cython"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%cython\n",
    "def g(int x):\n",
    "    return x ** 2 - x\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "37.7 ns ± 0.469 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit g(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy import Function, symbols, Eq, solve\n",
    "import mpmath\n",
    "import sys\n",
    "sys.modules['sympy.mpmath'] = mpmath\n",
    "# 声明符号变量\n",
    "a, b = symbols('a b')\n",
    "f = symbols('f', cls=Function)\n",
    "\n",
    "# 定义方程\n",
    "equation = Eq(f(2*a) + 2*f(b), f(f(a+b)))\n",
    "\n",
    "# 求解方程\n",
    "solution = solve(equation, f(a))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  },
  "vscode": {
   "interpreter": {
    "hash": "42d820d8758cde2badbeb8f7eaaa44975ccec32144b366942c17254cc50801f8"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
